<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="75px">
<!--      <el-form-item label="所属课程" prop="platformId" v-if="!platformId">
        <el-select v-model="queryParams.platformId" placeholder="请选择课程" clearable>
          <el-option v-for="item in platformList" :key="item.baseId" :label="item.title" :value="item.baseId">
            <span style="float: left">{{ item.title }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              <dict-tag :options="dict.type.bmzt" :value="item.applyStatus" />
            </span>
          </el-option>
        </el-select>
      </el-form-item>-->
      <el-form-item label="章节标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入章节标题" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:platformChapter:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['business:platformChapter:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:platformChapter:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['business:platformChapter:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button :disabled="multiple" type="info" plain icon="el-icon-document-add" size="mini"
          @click="handleCopy">一键复制章节
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="platformChapterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="baseId" v-if="false" />
      <el-table-column label="所属课程" align="center" prop="platformTitle" :show-overflow-tooltip="true" />
      <el-table-column label="章节标题" align="center" prop="title" :show-overflow-tooltip="true" />
      <el-table-column label="讲师名称" align="center" prop="lecturer" :show-overflow-tooltip="true" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:platformChapter:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:platformChapter:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改章节管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属课程" prop="platformId">
          <el-select style="width: 100%;" v-model="form.platformId" placeholder="请选择课程" clearable>
            <el-option v-for="item in platformList" :key="item.baseId" :label="item.title" :value="item.baseId">
              <span style="float: left">{{ item.title }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">
                <dict-tag :options="dict.type.bmzt" :value="item.applyStatus" />
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入章节标题" />
        </el-form-item>
        <el-form-item label="讲师名称" prop="lecturer">
          <el-input v-model="form.lecturer" placeholder="请输入讲师名称" />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="1" placeholder="请输入排序"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item required label="关联视频">
          <el-button type="primary" @click="handleVideo">添加</el-button>
        </el-form-item>
        <el-form-item>
          <el-table :data="discountDetails">
            <el-table-column label="序号" align="center" width="50px">
              <template slot-scope="scope">
                {{ scope.$index+1}}
              </template>
            </el-table-column>
            <el-table-column label="视频标题" align="center" prop="title" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ !scope.row.videoVo?scope.row.title:scope.row.videoVo.title}}
              </template>
            </el-table-column>
            <el-table-column label="视频时长(秒)" align="center" prop="duration">
              <template slot-scope="scope">
                {{ !scope.row.videoVo?scope.row.duration:scope.row.videoVo.duration}}
              </template>
            </el-table-column>
            <el-table-column label="观看程度(%)" align="center" prop="degree">
              <template slot-scope="scope">
                {{ !scope.row.videoVo?scope.row.degree:scope.row.videoVo.degree}}
              </template>
            </el-table-column>
            <el-table-column label="积分数" align="center" prop="points">
              <template slot-scope="scope">
                {{ !scope.row.videoVo?scope.row.points:scope.row.videoVo.points}}
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button type="text" style="padding:0" :disabled="scope.$index == 0"
                  @click="moveUpward(scope.row, scope.$index)">上移
                </el-button>
                <el-button type="text" style="padding:0" :disabled="(scope.$index + 1) == discountDetails.length"
                  @click="moveDown(scope.row, scope.$index)">下移
                </el-button>
                <el-button type="text" style="padding:0" @click="handleDeleteInfo(scope.$index)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改视频对话框 -->
    <el-dialog title="关联视频" :visible.sync="openInfo" width="50%" append-to-body>
      <el-form size="small" :inline="true" label-width="75px">
        <el-form-item label="视频标题">
          <el-input v-model="videoForm.title" placeholder="请输入视频标题" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="searchVideo">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-table :row-key="getRowKey" ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
        @selection-change="handleSelectionChange2">
        <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="50px">
          <template slot-scope="scope">
            {{ (videoForm.pageNum - 1)*videoForm.pageSize+scope.$index+1 }}
          </template>
        </el-table-column>
        <el-table-column label="视频标题" align="center" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="视频时长(秒)" align="center" prop="duration" />
        <el-table-column label="观看程度(%)" align="center" prop="degree" />
        <el-table-column label="积分数" align="center" prop="points" />
      </el-table>
      <pagination v-show="totalVideo>0" :total="totalVideo" :page.sync="videoForm.pageNum"
        :limit.sync="videoForm.pageSize" @pagination="getVideoList" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormInfo">确 定</el-button>
        <el-button @click="openInfo=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listPlatformChapter,
    getPlatformChapter,
    delPlatformChapter,
    addPlatformChapter,
    updatePlatformChapter,
    handleCopy
  } from "@/api/business/platformChapter";
  import {
    listPlatformVideo
  } from "@/api/business/platformVideo";
  import {
    platformList
  } from "@/api/business/platform";

  export default {
    name: "PlatformChapter",
    dicts: ['bmzt'],
    props: {
      platformId: {
        type: String,
        default: ""
      },
      activeName: {
        type: String,
        default: ""
      },
    },
    watch: {
      activeName: {
        handler: function(val, oldVal) {
          this.queryParams.platformId = this.platformId;
          if (val === 'second') {
            this.getList();
          }
        },
        immediate: true
      }
    },
    data() {
      return {
        // 课程列表
        platformList: [],
        tableData: [],
        discountDetails: [],
        openInfo: false,
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 章节管理表格数据
        platformChapterList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          platformId: this.platformId,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          lecturer: [{
            required: true,
            message: "讲师名称不能为空",
            trigger: "blur"
          }],
          platformId: [{
            required: true,
            message: "课程不能为空",
            trigger: "blur"
          }],
          title: [{
            required: true,
            message: "章节标题不能为空",
            trigger: "blur"
          }],
        },
        videoForm: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
        },
        totalVideo: 0,
        posts: []
      };
    },
    created() {
      this.getList();
      this.getPlatformList();
    },
    methods: {
      handleCopy() {
        const baseIds = this.ids;
        this.$modal.confirm('是否确认复制所选章节？').then(() => {
          this.loading = true;
          return handleCopy(baseIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("复制成功");
        }).catch(() => {}).finally(() => {
          this.loading = false;
        });
      },
      async handleVideo() {
        this.videoForm = {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
        }
        await this.getVideoList()
        this.openInfo = true
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection()
          this.tableData.forEach(row => {
            if (this.discountDetails.some(e => e.baseId == row.baseId)) {
              this.$refs.multipleTable.toggleRowSelection(row, true);
            }
          })
        })
      },
      getPlatformList() {
        platformList().then(response => {
          this.platformList = response.data;
        });
      },
      async getVideoList() {
        await listPlatformVideo(this.videoForm).then(response => {
          this.tableData = response.rows;
          this.totalVideo = response.total;
        });
      },
      // 指定一个key标识这一行的数据
      getRowKey(row) {
        return row.baseId
      },
      //视频搜索
      searchVideo() {
        this.videoForm.pageNum = 1
        this.getVideoList()
      },
      moveUpward(row, index) {
        if (index > 0) {
          let upData = this.discountDetails[index - 1]
          this.discountDetails.splice(index - 1, 1)
          this.discountDetails.splice(index, 0, upData)
        } else {
          this.$message({
            message: '已经是第一条，上移失败',
            type: 'warning'
          })
        }
      },
      moveDown(row, index) {
        if ((index + 1) == this.discountDetails.length) {
          this.$message({
            message: '已经是最后一条，下移失败',
            type: 'warning'
          })
        } else {
          let downData = this.discountDetails[index + 1]
          this.discountDetails.splice(index + 1, 1)
          this.discountDetails.splice(index, 0, downData)
        }
      },
      handleSelectionChange2(selection) {
        this.posts = selection;
      },
      /** 提交明细按钮 */
      submitFormInfo() {
        if (this.posts.length == 0) {
          this.$modal.msgError("请选择视频！");
        } else {
          this.discountDetails = this.posts
          this.openInfo = false;
        }
      },
      /** 删除明细按钮操作 */
      handleDeleteInfo(i) {
        this.$modal.confirm('是否确认删除该数据项？').then(() => {
          this.discountDetails.splice(i, 1);
        }).then(() => {
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {}).finally(() => {})
      },
      /** 查询章节管理列表 */
      getList() {
        this.loading = true;
        listPlatformChapter(this.queryParams).then(response => {
          this.platformChapterList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          baseId: undefined,
          platformId: undefined,
          title: undefined,
          lecturer: undefined,
          lecturerTro: undefined,
          sort: undefined,
          delFlag: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        };
        this.discountDetails = []
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.baseId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加章节管理";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const baseId = row.baseId || this.ids
        getPlatformChapter(baseId).then(response => {
          this.loading = false;
          this.form = response.data;
          if (this.form.chapterVideos) {
            this.discountDetails = this.form.chapterVideos
            this.discountDetails.map(item => {
              item.baseId = item.videoBaseId
            })
          }
          this.open = true;
          this.title = "修改章节管理";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.discountDetails.length == 0) {
              this.$modal.msgError("请关联视频！");
            } else {
              this.discountDetails.map((item, index) => {
                item.videoBaseId = item.baseId
                item.sort = index + 1
              })
              this.form.chapterVideos = this.discountDetails
              if (this.form.baseId != null) {
                updatePlatformChapter(this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              } else {
                addPlatformChapter(this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }).finally(() => {
                  this.buttonLoading = false;
                });
              }
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const baseIds = row.baseId || this.ids;
        this.$modal.confirm('是否确认删除章节管理编号为"' + baseIds + '"的数据项？').then(() => {
          this.loading = true;
          return delPlatformChapter(baseIds);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {}).finally(() => {
          this.loading = false;
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('business/platformChapter/export', {
          ...this.queryParams
        }, `platformChapter_${new Date().getTime()}.xlsx`)
      }
    }
  };
</script>
